home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12007 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.2 KB  |  45 lines

  1. Path: noc.netcom.net!news
  2. From: Tarang Deshpande <tarang@willows.com>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Arrays of strings (linking)
  5. Date: Wed, 27 Mar 1996 18:31:08 -0800
  6. Organization: NETCOM Network Operations
  7. Message-ID: <3159F9EC.1835@willows.com>
  8. References: <4jbkpg$5m7@news.ariadne-t.gr>
  9. NNTP-Posting-Host: daffy.willows.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0GoldB2 (Win95; I)
  14.  
  15. Arnellos Argiris-TEIA wrote:
  16. > I have problem writing a function that accepts two strings and then linking
  17. > them together in a new string. I must also return a pointer to this new
  18. > string. For example: if I pass "Hello" to string1 and "World" to string2
  19. > the function must return a pointer to "Hello World!".
  20. > Could anyone help me by giving me an example or any ideas.
  21. > TIA
  22. >               Argiris Arnellos
  23.  
  24. If you don't mind string1 being modified you could just use strcat
  25. otherwise use the following code.  Note that this function requires
  26. that the returned pointer be freed.
  27.  
  28. char* strjoin ( char *str1, char* str2 )
  29. {
  30.  
  31.     char *str = malloc ( strlen ( str1 ) + strlen ( str2 ) + 1 );
  32.  
  33.     if ( str )
  34.     {
  35.         *str = '\0';
  36.         strcat ( str, str1 );
  37.         strcat ( str, str2 );
  38.     }
  39.  
  40.     return ( str );
  41.  
  42. }
  43.